# -*- coding: utf-8 -*-

import os
import requests
import subprocess
import argparse

# 解析命令行参数
parser = argparse.ArgumentParser(description='Gitee 仓库文件下载器')
parser.add_argument('--owner', required=True, help='Gitee 仓库所有者')
parser.add_argument('--repo', required=True, help='Gitee 仓库名称')
parser.add_argument('--token', required=True, help='Gitee Access Token')
args = parser.parse_args()

# Gitee 仓库信息
owner = args.owner
repo = args.repo
path = ''  # 目标目录路径，空字符串表示根目录
# Gitee API URL
api_url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}'

# 请求头
headers = {'Authorization': f'token {args.token}'} if args.token else {}

def fetch_file_list(url, headers):
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        print(f'Failed to fetch file list: {response.status_code}')
        return []

def download_file(file_url, save_path):
    # 使用 aria2c 下载文件
    # gitee不支持 -x 参数，只能单线程下载
    result = subprocess.run(['aria2c', '--console-log-level=error', '--file-allocation=none', '-x', '1', '-j', '10', '-s', '10', '-k', '1M', '-c', '-d', save_path, file_url])
    if result.returncode != 0:
        print(f'Failed to download {file_url}')

def process_files(file_list, current_path=repo):
    if not os.path.exists(current_path):
        os.makedirs(current_path)
    
    for file_info in file_list:
        file_type = file_info['type']
        file_name = file_info['name']
        download_url = file_info['download_url']
        file_path = os.path.join(current_path, file_name)

        if file_type == 'file':
            # 创建保存文件的目录
            if current_path and not os.path.exists(current_path):
                os.makedirs(current_path)
            # 下载文件
            download_file(download_url, current_path)

if __name__ == '__main__':
    file_list = fetch_file_list(api_url, headers)
    if file_list:
        process_files(file_list)